package com.derbysoft.dswitch.adapter.ihg.web.action.admin.setting.config;

import com.derbysoft.dswitch.adapter.ihg.common.domain.ConfigInfo;
import com.derbysoft.dswitch.adapter.ihg.common.repository.ConfigRepository;
import com.derbysoft.dswitch.adapter.ihg.web.action.support.BaseAction;
import com.derbysoft.dswitch.adapter.ihg.web.model.config.Configuration;
import org.apache.struts2.convention.annotation.Action;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;


public class EditAction extends BaseAction {

    private static final String ROOM_TYPE_NAME_FIELD = "room_type_name_field";
    private static final String ROOM_RATE_DESCRIPTION = "ROOM_RATE_DESCRIPTION";

    @Autowired
    private ConfigRepository configRepository;

    private Configuration configuration;

    @Action("save")
    public String save() {
        configRepository.saveAll(configurationToConfigItems(configuration));
        return LIST;
    }

    private List<ConfigInfo> configurationToConfigItems(Configuration configuration) {
        List<ConfigInfo> configInfos = new ArrayList<ConfigInfo>();
        configInfos.add(configuration.getRoomTypeName());
        configInfos.add(configuration.getMatchPriorityConfig());
        check(configuration, configInfos);
        return configInfos;
    }

    private void check(Configuration configuration, List<ConfigInfo> configInfos) {
        if (configuration.getRoomTypeName().getName().equals(ROOM_TYPE_NAME_FIELD)
                && !configuration.getRoomTypeName().getValue().equals(ROOM_RATE_DESCRIPTION)) {
            configInfos.add(configuration.getAdditionalDetailCode());
        }
    }

    public Configuration getConfiguration() {
        return configuration;
    }

    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
    }
}
